package fun.yao.common.uitls;

import fun.yao.common.Constant;
import fun.yao.common.log.LogManager;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

public class LogUtil {

    /**
     * <p> 函数功能： 写日志  </p>
     * <p> 输入参数： 日志级别，日志信息 </p>
     * <p> 返回值： 无  </p>
     */
    public static void WriteLog(int iLevel,String logMsg)
    {
        writeLog("Gess", iLevel, logMsg );
    }

    /**
     * <p> 函数功能： 写日志  </p>
     * <p> 输入参数： 日志级别，异常信息 </p>
     * <p> 返回值： 无  </p>
     */
    public static void WriteLog(int iLevel,Exception e){
        LogUtil.WriteLog(iLevel,LogUtil.getExpStack(e));
    }

    /**
     * 写系统日志
     * @param iLevel
     * @param logMsg
     */
    public static void writeSystemLog(int iLevel,String logMsg)
    {
        LogUtil.writeLog(Constant.LF_SYSTEM,iLevel,logMsg);
    }

    /**
     * 写日志
     * @param sFileName 日志文件名称，请使用 Constant.LF_XXXX 常量
     * @param iLevel    日志级别
     * @param logMsg    日志信息
     */
    public static void writeLog(String sFileName,int iLevel,String logMsg)
    {
        if ( logMsg != null && Constant.CFG_LOG_LEVEL.indexOf(""+iLevel) >= 0 )
        {
            //add by csl 2010.8.5 屏蔽敏感字段的值
            if ( LogManager.getInstance().checkIsNeedFilterSecretKey() == true )
                logMsg = LogManager.getInstance().filterSecretKeyValue(logMsg);
            //end add

            //add by ljl 20171227 过滤日志长度
            logMsg = LogManager.getInstance().filterLogMsgLeng(logMsg);

            StringBuffer sb = new StringBuffer(logMsg.length() + 100);
            sb.append(DateUtil.getCalcDate(0,DateUtil.sdf_yyyy_MM_dd_hh_mm_ss_SS));
            sb.append(" [");
            sb.append(Thread.currentThread().getName());
            sb.append("] ");
            sb.append(logMsg);
            sb.append("\n");
            LogManager.getInstance().addLog(sFileName, sb);

            if ( Constant.BADLY_ERROR == iLevel || Constant.NORMAL_ERROR == iLevel )
                LogManager.getInstance().addLog(Constant.LF_ERROR, new StringBuffer(sb.toString()));

            if ( Constant.NOTICE == iLevel || Constant.BADLY_ERROR == iLevel )
            {
                try{
                    System.out.print(new String(sb.toString().getBytes(Constant.CFG_CHARSET_NAME),Constant.CFG_CHARSET_NAME));
                }catch(Exception e){

                }
            }

        }
    }

    /**
     * <p> 函数功能：获得异常的详细信息</p>
     * <p> 输入参数：e 异常对象</p>
     * <p> 返回值：将异常的堆栈信息转为字符串</p>
     */
    public static String getExpStack(Exception e) {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(bo);
        e.printStackTrace(pw);
        pw.flush();
        pw.close();
        return bo.toString();
    }

}
